﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Text;
using System.Linq;
using Microsoft.Office.PowerPoint.STAMP.Controls;

namespace Microsoft.Office.PowerPoint.STAMP.Common
{
    /// <summary>
    /// Provides access to the installed font library.
    /// </summary>
    public static class FontService
    {
        /// <summary>
        /// Gets the available fonts.
        /// </summary>
        public static IEnumerable<FontFamily> AvailableFonts
        {
            get { return new InstalledFontCollection().Families.ToList(); }
        }

        /// <summary>
        /// Loads the default font.
        /// </summary>
        /// <value></value>
        public static FontFamily DefaultFont
        {
            get
            {
                IEnumerable<FontFamily> availableFonts = AvailableFonts;
                Font primaryDefaultFont = Properties.Settings.Default.DefaultFont;
                return availableFonts.FirstOrDefault(familyItem => familyItem.Name.Equals(primaryDefaultFont.FontFamily.Name))
                       ?? availableFonts.First();
            }
        }

        /// <summary>
        /// Loads the font.
        /// </summary>
        /// <param name="fontName">Name of the font.</param>
        /// <returns></returns>
        public static FontFamily LoadFont(string fontName)
        {
            return
                AvailableFonts.FirstOrDefault(
                    familyItem => familyItem.Name.Equals(fontName, StringComparison.InvariantCultureIgnoreCase));
        }

        /// <summary>
        /// Loads the font style.
        /// </summary>
        /// <param name="formatting">The formatting.</param>
        /// <param name="currentFontStyle">The current font style.</param>
        /// <returns></returns>
        public static FontStyle LoadFontStyle(FormattingToolbarSelection formatting, FontStyle currentFontStyle)
        {
            FontStyle fontStyle = currentFontStyle;
            fontStyle = UpdateFontStyle(FontStyle.Bold, formatting.IsBold, fontStyle);
            fontStyle = UpdateFontStyle(FontStyle.Italic, formatting.IsItalic, fontStyle);
            fontStyle = UpdateFontStyle(FontStyle.Underline, formatting.IsUnderline, fontStyle);
            return fontStyle;
        }

        private static FontStyle UpdateFontStyle(FontStyle fontStyleMember, bool? fontStyleApplies, FontStyle currentFontStyle)
        {
            if (!fontStyleApplies.HasValue)
                return currentFontStyle;
            if (fontStyleApplies.Value)
                return currentFontStyle | fontStyleMember;
            return currentFontStyle & ~fontStyleMember;
        }
    }
}